{# @copyright   Copyright (C) 2010-2020 Combodo SARL #}
{# @license     http://opensource.org/licenses/AGPL-3.0 #}
{% set sListId = oUIBlock.GetOption('sListId') %}
{% if oUIBlock.GetOption("iPageSize") is not empty %}
	{% set iPageSize = oUIBlock.GetOption("iPageSize") %}
{% else %}
	{% set iPageSize = 10 %}
{% endif %}

$('#{{ oUIBlock.GetId() }}').closest("[role=dialog]").on("dialogbeforeclose", function () {
    $('#{{ oUIBlock.GetId() }}').DataTable().clear();
});

$('#{{ sListId }}').data('target', 'ibo-datatables--outer');

if ($.fn.dataTable.isDataTable('#{{ oUIBlock.GetId() }}')) {
    $('#{{ oUIBlock.GetId() }}').DataTable().destroy(false);
}

var oTable{{ sListId }} = $('#{{ oUIBlock.GetId() }}').DataTable({
    language: {
        processing: "{{ 'UI:Datatables:Language:Processing'|dict_s }}",
        search: "{{ 'UI:Datatables:Language:Search'|dict_s }}",
        lengthMenu: "{{ 'UI:Datatables:Language:LengthMenu'|dict_s }}",
        zeroRecords: "{{ 'UI:Datatables:Language:ZeroRecords'|dict_s }}",
        info: "{{ 'UI:Datatables:Language:Info'|dict_s }}",
        infoEmpty: "{{ 'UI:Datatables:Language:InfoEmpty'|dict_s }}",
        infoFiltered: "({{ 'UI:Datatables:Language:InfoFiltered'|dict_s }})",
        emptyTable: "{{ 'UI:Datatables:Language:EmptyTable'|dict_s }}",
        paginate: {
            first: "<<",
            previous: "<i class=\"fas fa-angle-left\"></i>",
            next: "<i class=\"fas fa-angle-right\"></i>",
            last: ">>"
        },
        aria: {
            sortAscending: ": {{ 'UI:Datatables:Language:Sort:Ascending'|dict_s }}",
            sortDescending: ": {{ 'UI:Datatables:Language:Sort:Descending'|dict_s }}"
        }
    },
    lengthMenu: [[ {{ iPageSize }},  {{ iPageSize*2 }},  {{ iPageSize*3 }}, {{ iPageSize*4 }}, -1], [ {{ iPageSize }},  {{ iPageSize*2 }},  {{ iPageSize*3 }}, {{ iPageSize*4 }}, "{{ 'Portal:Datatables:Language:DisplayLength:All'|dict_s }}"]],
    dom: "<'ibo-datatable-toolbar'pil>t<'ibo-datatable-toolbar'pil>",
    {% if( oUIBlock.GetOptions("sort")[0] is defined ) %}
    order: [[{{ oUIBlock.GetOptions()["sort"][0] }}, '{{ oUIBlock.GetOptions()["sort"][1] }}']],
    {% else %}
    order: [],
    {% endif %}
    ordering: true,
    {% if oUIBlock.GetOption("select_mode") is not empty %}
    select: {
        style: "{{ oUIBlock.GetOption("select_mode") }}"
    },
    rowCallback: function (oRow, oData) {
        if ($(this).closest('.ibo-panel--body').find('[name=selectionMode]').val() === "negative") {
            if (oSelectedItems{{ sListId }}.indexOf(oData.id) === -1) {
                $(oRow).select();
                $(oRow).find('td:first-child input').prop('checked', true);
            }
        } else {
            if (oSelectedItems{{ sListId }}.indexOf(oData.id) > -1) {
                $(oRow).select();
                $(oRow).find('td:first-child input').prop('checked', true);
            }
        }
    },
    drawCallback: function () {
        if ($(this).closest('.ibo-panel--body').find('[name=selectionMode]').val() === "negative") {
            $(this).find('[name=selectAll]').prop('checked', true);
            $(this).DataTable().rows({page: 'current'}).select();
        } else {
            $(this).closest('.dataTables_wrapper').find('.dataTables_paginate, .dataTables_info').show();
        }
    },
    {% endif %}
    rowId: "id",
    filter: false,
    retrieve: true,
    destroy: true,
    processing: true,
    serverSide: true,
    columns: [
        {% if oUIBlock.GetOption("select_mode") is not empty %}
        {
            width: "20px",
            searchable: false,
            sortable: false,
            title:
            {% if oUIBlock.GetOption("select_mode") != "single" %}
                '<span class="row_input"><input type="checkbox" onclick="checkAllDataTable(\'{{ oUIBlock.GetId() }}\',this.checked,\'{{ oUIBlock.GetOption("sListId") }}\');" class="checkAll" id="field_{{ oUIBlock.GetId() }}_check_all" name="field_{{ oUIBlock.GetId() }}_check_all" title="{{ 'UI:SearchValue:CheckAll'|dict_s }} / {{ 'UI:SearchValue:UncheckAll'|dict_s }}"></span>'
            {% else %}
                '<span class="row_input"><input type="checkbox" style="display: none;" onclick="checkAllDataTable(\'{{ oUIBlock.GetId() }}\',this.checked,\'{{ oUIBlock.GetOption("sListId") }}\');" class="checkAll" id="field_{{ oUIBlock.GetId() }}_check_all" name="field_{{ oUIBlock.GetId() }}_check_all" title="{{ 'UI:SearchValue:CheckAll'|dict_s }} / {{ 'UI:SearchValue:UncheckAll'|dict_s }}"></span>'
            {% endif %},
            type: "html",
            data: "",
            render: function (data, type, row) {
                let oCheckboxElem =
                {% if oUIBlock.GetOption("select_mode") != "single" %}
                    $('<span class="row_input"><input type="checkbox" class="selectList{{ oUIBlock.GetId() }}" name="selectObject[]" value="'+row.id+'"></span>');
                {% else %}
                     $('<span class="row_input"><input type="radio" class="selectList{{ oUIBlock.GetId() }}" name="selectObject[]" value="'+row.id+'"></span>');
                {% endif %}
                if (row.limited_access) {
                    oCheckboxElem.html('-');
                } else {
                    oCheckboxElem.find(':input').attr('data-object-id', row.id).attr('data-target-object-id', row.target_id);
                }
                return oCheckboxElem.prop('outerHTML');
            }
        },
        {% endif %}
        {% for aColumn in oUIBlock.GetDisplayColumns() %}
        {
            width: "auto",
            searchable: false,
            sortable: true,
            title: "{{ aColumn["attribute_label"] }}",
            defaultContent: "",
            type: "html",
            metadata: {
                object_class: "{{ aColumn["object_class"] }}",
                attribute_code: "{{ aColumn["attribute_code"] }}",
                attribute_type: "{{ aColumn["attribute_type"] }}",
                attribute_label: "{{ aColumn["attribute_label"] }}"
            },
            data: "{{ aColumn["class_alias"] }}/{{ aColumn["attribute_code"] }}",
            render: {
                display: function (data, type, row) {  {{ aColumn["render"]|raw }}},
                _: "{{ aColumn["class_alias"] }}/{{ aColumn["attribute_code"] }}"
            }
        },
        {% endfor %}
    ],
    ajax: $.fn.dataTable.pipeline({
        url: "{{ oUIBlock.GetAjaxUrl() }}",
        data: {{ oUIBlock.GetJsonAjaxData() |raw }},
        method: "post",
        pages: 5 // number of pages to cache
    }),
    initComplete: function () {
	    if (this.api().page.info().pages < 2) {
            this.parent().find('.dataTables_paginate').hide();
            this.parent().find('.dataTables_length').hide();
        }
    }
});



{% if oUIBlock.GetOption("select_mode") is not empty %}
	{% if oUIBlock.GetOption("select_mode") != "single" %}
		oTable{{ sListId }}.off('select').on('select', function (oEvent, dt, type, indexes) {
			let aData = oTable{{ sListId }}.rows(indexes).data().toArray();
			if( $(this).closest('.ibo-panel--body').find('[name=selectionMode]').val() === "negative")
		    {
			     // Checking input
			    $('#{{ oUIBlock.GetId() }} tr[role="row"].selected td:first-child input').prop('checked', true);
			    // Saving values in temp array
			    for (let i in aData) {
				    let iItemId = aData[i].id;
				    if (oSelectedItems{{ sListId }}.indexOf(iItemId) > -1) {
					    oSelectedItems{{ sListId }}.splice(oSelectedItems{{ sListId }}.indexOf(iItemId), 1);
					    updateDataTableSelection('{{ sListId }}');
				    }
			    }
		    }
			else {
			     // Checking input
			    $('#{{ oUIBlock.GetId() }} tr[role="row"].selected td:first-child input').prop('checked', true);
			    // Saving values in temp array
			    for (let i in aData) {
				    let iItemId = aData[i].id;
				    if (oSelectedItems{{ sListId }}.indexOf(iItemId) === -1) {
					    oSelectedItems{{ sListId }}.push(iItemId);
                        updateDataTableSelection('{{ sListId }}');
				    }
			    }
		    }
		});

		oTable{{ sListId }}.off('deselect').on('deselect', function (oEvent, dt, type, indexes) {
			let aData = oTable{{ sListId }}.rows(indexes).data().toArray();

			// Checking input
			$('#{{ oUIBlock.GetId() }} tr[role="row"]:not(.selected) td:first-child input').prop('checked', false);
			// Saving values in temp array
			if ($(this).closest('.ibo-panel--body').find('[name=selectionMode]').val() === "negative") {
				for (let i in aData) {
					let iItemId = aData[i].id;
					if (oSelectedItems{{ sListId }}.indexOf(iItemId) === -1) {
						oSelectedItems{{ sListId }}.push(iItemId);
                        updateDataTableSelection('{{ sListId }}');
					}
				}
			} else {
				for (let i in aData) {
                    let iItemId = aData[i].id;
					if (oSelectedItems{{ sListId }}.indexOf(iItemId) > -1) {
						oSelectedItems{{ sListId }}.splice(oSelectedItems{{ sListId }}.indexOf(iItemId), 1);
                        updateDataTableSelection('{{ sListId }}');
					}
				}
			}
		});
	{% else %}
		oTable{{ sListId }}.off('select').on('select', function (oEvent, dt, type, indexes) {
            let aData = oTable{{ sListId }}.rows(indexes).data().toArray();
			// Checking input
			$('#{{ oUIBlock.GetId() }} tr[role="row"].selected td:first-child input').prop('checked', true);
			// Saving values in temp array
			for (let i in aData) {
                let iItemId = aData[i].id;
				if (oSelectedItems{{ sListId }}.indexOf(iItemId) === -1) {
					oSelectedItems{{ sListId }}.push(iItemId);
                    updateDataTableSelection('{{ sListId }}');
				}
			}
		});

		oTable{{ sListId }}.off('deselect').on('deselect', function (oEvent, dt, type, indexes) {
            let aData = oTable{{ sListId }}.rows(indexes).data().toArray();

			// Checking input
			$('#{{ oUIBlock.GetId() }} tr[role="row"]:not(.selected) td:first-child input').prop('checked', false);
			// Saving values in temp array
			for (let i in aData) {
                let iItemId = aData[i].id;
				if (oSelectedItems{{ sListId }}.indexOf(iItemId) > -1) {
					oSelectedItems{{ sListId }}.splice(oSelectedItems{{ sListId }}.indexOf(iItemId), 1);
                    updateDataTableSelection('{{ sListId }}');
				}
			}
		});
	{% endif %}

    {% if oUIBlock.GetOption('sCountSelector') is not empty %}
        $('#{{ sListId }} [name="selectionCount"]').bind('change', function() {
            $('{{ oUIBlock.GetOption('sCountSelector') }}').val($('#{{ sListId }} [name="selectionCount"]').val());
            $('{{ oUIBlock.GetOption('sCountSelector') }}').trigger('change');
        });
    {% endif %}

{% endif %}

$('#datatable_dlg_{{ oUIBlock.GetId() }}').dialog(
    {
        autoOpen: false,
        title: "{{ 'UI:ListConfigurationTitle'|dict_s }}",
        width: 500,
	    open: function(){
		    $('#datatable_dlg_{{ oUIBlock.GetId() }}').find('[name=action]').val("none");
	    },
        close: function (event, ui) { //save data and refresh
			if( $('#datatable_dlg_{{ oUIBlock.GetId() }}').find('[name=action]').val() === "none") {
				$('#datatable_dlg_{{ oUIBlock.GetId() }}').DataTableSettings('onDlgCancel');
            }
        }
    });

$aOptions = {
    sListId: '{{ oUIBlock.GetId() }}',
    oColumns: {{ oUIBlock.GetResultColumnsAsJson()|raw }},
    sSelectMode: "{{ oUIBlock.GetOption("select_mode") }}",
    sViewLink: '{{ oUIBlock.GetOption("bViewLink") }}',
    iPageSize: '{{ oUIBlock.GetOption("iPageSize") }}',
    oClassAliases: JSON.parse('{{ oUIBlock.GetOption("oClassAliases") |raw }}'),
    sTableId: '{{ oUIBlock.GetOption("sTableId") }}',
    //oExtraParams
    sRenderUrl: "{{ oUIBlock.GetAjaxUrl() }}",
    oData: {{ oUIBlock.GetJsonAjaxData() |raw }},
    oDefaultSettings: {{ oUIBlock.GetOption("oDefaultSettings")|raw }},
    oLabels: {moveup: "{{ 'UI:Button:MoveUp'|dict_s }}", movedown: "{{ 'UI:Button:MoveDown'|dict_s }}"},
};

$('#datatable_dlg_{{ oUIBlock.GetId() }}').DataTableSettings($aOptions);